package top.anydata.lifeofcode.lifesystem.web.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.security.web.util.matcher.RegexRequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import top.anydata.lifeofcode.lifesystem.conf.ConstansKey;
import top.anydata.lifeofcode.lifesystem.conf.global.exception.DecryptException;
import top.anydata.lifeofcode.lifesystem.dto.sys.app.SysAppDetailDto;
import top.anydata.lifeofcode.lifesystem.service.sys.app.ISysAppAdminService;
import top.anydata.lifeofcode.lifesystem.service.sys.user.IJwtTokenService;
import top.anydata.lifeofcode.lifesystem.util.EncryptUtils;
import top.anydata.lifeofcode.lifesystem.web.requests.api.AppRequestWrapper;
import top.anydata.lifeofcode.lifesystem.web.requests.api.AppResponseWrapper;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.stream.Collectors;

/**
 * 功能描述:
 *
 * @author <a href="mailto:caingao@anydata.top">CainGao</a>
 * @version V_1.0
 * @date 2024/5/7 4:26 PM
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AppAuthenticationFilter extends OncePerRequestFilter {

    private final ISysAppAdminService sysAppAdminService;


    @Override
    protected void doFilterInternal(@NotNull HttpServletRequest request,
                                    @NotNull HttpServletResponse response,
                                    @NotNull FilterChain filterChain) throws ServletException, IOException {
        if (!RegexRequestMatcher.regexMatcher(ConstansKey.APP_URL_PATTERN).matches(request)) {
            filterChain.doFilter(request, response);
            return;
        }

        String aesKey = request.getHeader("us_ae");
        String appId = extractAppId(request.getRequestURI());
        SysAppDetailDto sysAppDetailDto = sysAppAdminService.getSysAppDetail(appId);
        try {
            if (sysAppDetailDto != null) {
                String privateKey = sysAppDetailDto.getPrivateKey();
                BufferedReader reader = request.getReader();
                String decryptedRequestBody = EncryptUtils.rsaDecrypt(reader.lines().collect(Collectors.joining()), privateKey);
                AppRequestWrapper appRequestWrapper = new AppRequestWrapper(request, decryptedRequestBody);
                filterChain.doFilter(appRequestWrapper, response);
            } else {
                filterChain.doFilter(request, response);
            }
        } catch (DecryptException e) {
            log.error("Decryption failed", e);
            throw e;
        } catch (Exception e) {
            log.error("An error occurred during encryption/decryption", e);
            throw new ServletException("Encryption/Decryption error", e);
        }
    }

    private String extractAppId(String pathInfo) {
        // Extract the app ID from the request URI
        // This should be adapted to match the expected URI structure
        String[] parts = pathInfo.split("/");
        if (parts.length > 2) {
            return parts[2];
        }
        return "";
    }
}
